package com.edu.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.edu.common.config.ProjectConfig;
import com.edu.common.utils.VideoGenerator;
import com.edu.common.utils.file.FileTypeUtils;
import com.edu.common.utils.file.FileUploadUtils;
import com.edu.common.utils.file.ImageUtils;
import com.edu.system.domain.FileInfo;
import com.edu.system.domain.THighlights;
import com.edu.system.domain.dto.HighlightsDTO;
import com.edu.system.mapper.THighlightsMapper;
import com.edu.system.service.ITHighlightsService;
import com.edu.system.service.ITPublishClassService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 校园风采Service业务层处理
 * 
 * @author xxxx
 * @date 2023-12-27
 */
@Slf4j
@Service
public class THighlightsServiceImpl implements ITHighlightsService 
{
    @Autowired
    private THighlightsMapper tHighlightsMapper;
    @Resource
    private ITPublishClassService publishClassService;

    @Value("${avatar.mp4CoverDefault}")
    private String coverDefaultImg;
    @Value("${image.host}")
    private String imageHost;

    // 1通知 2校园风采
    public static Integer publishClass_type=2;

    // "发布状态 0:待发布 1:已发布"
    public static Integer publishStatus_on=1;
    public static Integer publishStatus_off=0;

    //"状态 0:下架 1:上架"
    public static Integer status_on = 1;
    public static Integer status_off = 0;

    /**
     * 查询校园风采
     * 
     * @param id 校园风采主键
     * @return 校园风采
     */
    @Override
    public HighlightsDTO selectTHighlightsById(Long id)
    {
        THighlights h = tHighlightsMapper.selectTHighlightsById(id);
        HighlightsDTO dto = BeanUtil.copyProperties(h, HighlightsDTO.class, "filePath");
        if (StrUtil.isNotBlank(h.getFilePath())){
            dto.setFilePath(JSONArray.parseArray(h.getFilePath(), FileInfo.class));
        }
        return dto;
    }

    @Override
    public List<THighlights> liveListByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }

        return tHighlightsMapper.listByIds(ids)
            .stream()
            .filter(a -> a.getStatus().equals(status_on))
            .filter(a -> a.getStartTime() != null && new Date().getTime() >= a.getStartTime().getTime())
            .filter(a -> a.getEndTime() != null && new Date().getTime() <= a.getEndTime().getTime())
            .collect(Collectors.toList());
    }

    @Override
    public List<THighlights> listByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new ArrayList<>();
        }
        return tHighlightsMapper.listByIds(ids);
    }

    /**
     * 查询校园风采列表
     * 
     * @param tHighlights 校园风采
     * @return 校园风采
     */
    @Override
    public List<THighlights> selectTHighlightsList(THighlights tHighlights)
    {
        return tHighlightsMapper.selectTHighlightsList(tHighlights);
    }

    /**
     * 新增校园风采
     * 
     * @param h 校园风采
     * @return 结果
     */
    @Override
    public int insertTHighlights(HighlightsDTO h)
    {
        THighlights highlights = BeanUtil.copyProperties(h, THighlights.class, "filePath");

        if (CollectionUtils.isNotEmpty(h.getFilePath())){
            h.getFilePath().forEach(a -> {
                if (FileTypeUtils.getFileType(a.getUrl()).equals("mp4") && StrUtil.isBlank(a.getCoverUrl())){

                    String viewPath = buildCoverImg(a.getUrl());
                    viewPath = StrUtil.isBlank(viewPath) ? ImageUtils.getDefaultImage(coverDefaultImg) : viewPath;
                    // 封面
                    a.setCoverUrl(viewPath);
                }
            });

            highlights.setFilePath(JSONArray.toJSONString(h.getFilePath()));
        }
        return tHighlightsMapper.insertTHighlights(highlights);
    }

    private String buildCoverImg(String url) {
        // 视频的存储地址
        String videoSavePath = FileUploadUtils.getRealPath(url);
        // 封面地址
        String filePath = ProjectConfig.getUploadPath();
        String fileName = FileUploadUtils.extractFilename("jpg");
        String saveRealPath = filePath + "/" + fileName;
        String viewPath = "";
        try {
            VideoGenerator.generateCover(videoSavePath, saveRealPath);
            viewPath = "/prod-api" + FileUploadUtils.getPathFileName(filePath, fileName);
        }catch (Exception e){
            log.error("自动获取视频封面异常：{}", e.getMessage(), e);
        }
        return viewPath;
    }

    /**
     * 修改校园风采
     * 
     * @param h 校园风采
     * @return 结果
     */
    @Override
    public int updateTHighlights(HighlightsDTO h)
    {
        THighlights highlights = BeanUtil.copyProperties(h, THighlights.class, "filePath");

        if (CollectionUtils.isNotEmpty(h.getFilePath())){
            h.getFilePath().forEach(a -> {
                if (FileTypeUtils.getFileType(a.getUrl()).equals("mp4") && StrUtil.isBlank(a.getCoverUrl())){
                    a.setCoverUrl(ImageUtils.getDefaultImage(coverDefaultImg));
                }
            });

            highlights.setFilePath(JSONArray.toJSONString(h.getFilePath()));
        }
        return tHighlightsMapper.updateTHighlights(highlights);
    }

    @Override
    public int publishStatusToOn(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return 0;
        }
        THighlights l = new THighlights();
        l.setPublishStatus(publishStatus_on);
        l.setPublishTime(new Date());
        return tHighlightsMapper.publishByIds(ids, l);
    }

    /**
     * 批量删除校园风采
     * 
     * @param ids 需要删除的校园风采主键
     * @return 结果
     */
    @Override
    public int deleteTHighlightsByIds(Long[] ids)
    {
        Stream.of(ids)
            .forEach(id -> {
                publishClassService.deleteTPublishClass(id, publishClass_type);
            });
        return tHighlightsMapper.deleteTHighlightsByIds(ids);
    }

    /**
     * 删除校园风采信息
     * 
     * @param id 校园风采主键
     * @return 结果
     */
    @Override
    public int deleteTHighlightsById(Long id)
    {
        publishClassService.deleteTPublishClass(id, publishClass_type);
        return tHighlightsMapper.deleteTHighlightsById(id);
    }

    @Override
    public List<THighlights> queryTodayChangeList() {
        Date date = new Date();
        DateTime beginTime = DateUtil.beginOfDay(date);
        DateTime endTime = DateUtil.endOfDay(date);
        return tHighlightsMapper.needStatusChangeList(beginTime, endTime);
    }
}
